#include "UsersRegister.hpp"
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <string>

namespace managerSystem {


// user类的构造函数实现
user::user(const std::string &user_id) {
  // 使用绝对路径加载用户JSON文件
  std::string filePath =
      "/home/ccy/code_workspace/cpp_finall/resource/user/" + user_id + ".json";
  read_from_file(filePath, user_json_);
  user_id_ = user_json_["user_id"];
  user_name_ = user_json_["user_name"];
  user_phone_ = user_json_["user_phone"];
  user_password_ = user_json_["user_password"];
  user_email_ = user_json_["user_email"];
  user_province_ = user_json_["user_province"];
  user_points_ = user_json_["user_points"];
  user_wants_major_ = user_json_["user_wants_major"];

  // 读取用户状态，如果不存在则默认为"active"
  if (user_json_.contains("status")) {
    user_status_ = user_json_["status"];
  } else {
    user_status_ = "active";
  }
}

user::user(const std::string &user_name, const std::string &user_phone,
           const std::string &user_password, const std::string &user_email,
           const std::string &user_province, const std::string &user_points,
           const std::string &user_wants_major) {
  user_name_ = user_name;
  user_phone_ = user_phone;
  user_password_ = user_password;
  user_email_ = user_email;
  user_province_ = user_province;
  user_points_ = user_points;
  user_wants_major_ = user_wants_major;
  user_status_ = "active"; // 新注册用户默认状态为"active"
}

// 重载输出运算符的实现
std::ostream &operator<<(std::ostream &os, const user &u) {
  os << "user_id: " << u.user_id_ << "\n"
     << "user_name: " << u.user_name_ << "\n"
     << "user_phone: " << u.user_phone_ << "\n"
     << "user_password: " << u.user_password_ << "\n"
     << "user_email: " << u.user_email_ << "\n"
     << "user_province: " << u.user_province_ << "\n"
     << "user_points: " << u.user_points_ << "\n"
     << "user_wants_major: " << u.user_wants_major_ << "\n"
     << "status: " << u.user_status_ << "\n";
  return os;
}

// usersManager类的构造函数实现
usersManager::usersManager() {
  // 用户文件所在的目录绝对路径
  std::string userDir = "/home/ccy/code_workspace/cpp_finall/resource/user/";

  // 遍历目录下的所有文件
  for (const auto &entry : std::filesystem::directory_iterator(userDir)) {
    if (entry.is_regular_file() && entry.path().extension() == ".json") {
      std::string filename = entry.path().filename().string();

      // 跳过用户索引文件
      if (filename == "users.json") {
        continue;
      }

      // 读取用户JSON文件
      nlohmann::json userJson;
      read_from_file(entry.path().string(), userJson);

      if (userJson.contains("user_id") && userJson.contains("user_name")) {
        std::string userId = userJson["user_id"].get<std::string>();
        std::string userName = userJson["user_name"].get<std::string>();

        // 添加到用户ID列表和映射
        user_ids_lists_.push_back(std::stoll(userId));
        user_id_name_map_[userId] = userName;
      }
    }
  }

  // 更新用户列表JSON
  users["users_id"] = user_ids_lists_;
  users["user_id_name_map"] = user_id_name_map_;
}

// usersRegister方法的实现
std::string usersManager::usersRegister(const std::string &user_name,
                                        const std::string &user_phone,
                                        const std::string &user_password,
                                        const std::string &user_email,
                                        const std::string &user_province,
                                        const std::string &user_points,
                                        const std::string &user_wants_major) {
  std::string log;
  // 使用当前时间作为随机数种子
  std::srand(static_cast<unsigned int>(std::time(nullptr)));
  // 生成一个随机ID - 6位数字
  long long random_id = 100000 + std::rand() % 900000;

  // 确保ID不重复
  while (std::find(user_ids_lists_.begin(), user_ids_lists_.end(), random_id) !=
         user_ids_lists_.end()) {
    random_id = 100000 + std::rand() % 900000;
  }

  // TODO :检查用户名是否已存在
  usersManager um;
  if (um.getUserIdByName(user_name) != "") {
    log = "Username already exists";
  }
  // 将新ID添加到用户ID列表中
  user_ids_lists_.push_back(random_id);

  // 创建新用户的JSON对象
  nlohmann::json new_user_json;
  new_user_json["user_id"] = std::to_string(random_id);
  new_user_json["user_name"] = user_name;
  new_user_json["user_phone"] = user_phone;
  new_user_json["user_password"] = user_password;
  new_user_json["user_email"] = user_email;
  new_user_json["user_province"] = user_province;
  new_user_json["user_points"] = user_points;
  new_user_json["user_wants_major"] = user_wants_major;
  new_user_json["status"] = "active"; // 设置默认状态为"active"

  // 更新用户ID与用户名的映射关系
  std::string id_str = std::to_string(random_id);
  user_id_name_map_[id_str] = user_name;

  // 更新用户列表和映射关系
  users["users_id"] = user_ids_lists_;
  users["user_id_name_map"] = user_id_name_map_;
  write_to_file("/home/ccy/code_workspace/cpp_finall/resource/user/users.json",
                users);

  // 创建用户文件
  write_to_file("/home/ccy/code_workspace/cpp_finall/resource/user/" + id_str +
                    ".json",
                new_user_json);
  //创建History目录
  std::string history_dir =
      "/home/ccy/code_workspace/cpp_finall/resource/History/users/" + id_str;
  std::filesystem::create_directories(history_dir);

  // 创建并返回用户对象
  static user new_user(id_str);
  log = "User registered successfully";
  return log;
}

// usersDelete方法的实现
std::string usersManager::usersDelete(const std::string &user_id,
                                      const std::string &user_password) {
  // 检查用户是否存在
  if (std::find(user_ids_lists_.begin(), user_ids_lists_.end(),
                std::stoll(user_id)) == user_ids_lists_.end()) {
    std::cerr << "User ID not found: " << user_id << std::endl;
    return "User ID not found";
  }
  //验证密码
  user user_temp(user_id);
  if (user_temp.get_user_password() != user_password) {
    std::cerr << "Password is incorrect: " << user_id << std::endl;
    return "Password is incorrect";
  }

  // 删除用户文件
  std::string file_path =
      "/home/ccy/code_workspace/cpp_finall/resource/user/" + user_id + ".json";
  if (std::remove(file_path.c_str()) != 0) {
    std::cerr << "Error deleting file: " << file_path << std::endl;
    return "Error deleting file";
  } else {
    std::cout << "File deleted successfully: " << file_path << std::endl;
  }

  // 更新用户列表
  auto it = std::remove(user_ids_lists_.begin(), user_ids_lists_.end(),
                        std::stoll(user_id));
  user_ids_lists_.erase(it, user_ids_lists_.end());

  // 删除用户ID和用户名的映射关系
  user_id_name_map_.erase(user_id);

  // 更新JSON数据
  users["users_id"] = user_ids_lists_;
  users["user_id_name_map"] = user_id_name_map_;
  write_to_file("/home/ccy/code_workspace/cpp_finall/resource/user/users.json",
                users);
  return "User deleted successfully";
}

// 通过用户名查找用户ID
std::string usersManager::getUserIdByName(const std::string &user_name) {
  for (auto &[id, name] : user_id_name_map_) {
    if (name == user_name) {
      return id;
    }
  }
  return ""; // 如果没有找到，返回空字符串
}

// 通过用户ID查找用户名
std::string usersManager::getUserNameById(const std::string &user_id) {
  if (user_id_name_map_.find(user_id) != user_id_name_map_.end()) {
    return user_id_name_map_[user_id];
  }
  return ""; // 如果没有找到，返回空字符串
}

} // namespace managerSystem